package org.smile.tomcat.session;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.catalina.util.CustomObjectInputStream;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.smile.tomcat.session.redis.RedisManager;
/**
 * jdk序列化实现
 * @author 胡真山
 *
 */
public class JdkSerializer implements Serializer<Object>{
	/**日志*/
	protected final Log logger = LogFactory.getLog(RedisManager.class);
	/**反序列化时类加载器,需要设置容器的加载器,不然会找不到项目的中的定义 的类名*/
	private ClassLoader loader;
	@Override
	public Object deserialize(byte[] datas) throws SerializeException {
		ByteArrayInputStream is = new ByteArrayInputStream(datas); 
		ObjectInputStream ois =null;
		try{
			if(this.loader!=null){
				//有类加载器时使用
				ois=new CustomObjectInputStream(is, loader);
			}else{
				ois=new ObjectInputStream(is);
			}
			return ois.readObject();
		} catch (IOException e) {
			throw new SerializeException(e);
		} catch (ClassNotFoundException e) {
			throw new SerializeException(e);
		}finally{
			try{
				ois.close();
			}catch(IOException e){
				logger.error(e);
			}
		}
	}

	@Override
	public byte[] serialize(Object obj) throws SerializeException {
		ByteArrayOutputStream is = new ByteArrayOutputStream(128); 
		ObjectOutputStream ois =null;
		try{
			ois= new ObjectOutputStream(is);
			ois.writeObject(obj);
			return is.toByteArray();
		} catch (IOException e) {
			throw new SerializeException(e);
		}finally{
			try{
				ois.close();
			}catch(IOException e){
				logger.error(e);
			}
		}
	}
	@Override
	public void setLoader(ClassLoader loader) {
		this.loader = loader;
	}
	
}
